<template>
  <div class="mobile-questionnaire-detail">
    <van-nav-bar 
      title="问卷填写" 
      left-text="返回"
      left-arrow
      @click-left="goBack"
    >
      <template #right>
        <van-button size="small" type="primary" @click="goStats" v-if="questionnaire">统计</van-button>
      </template>
    </van-nav-bar>
    <div class="content" v-if="questionnaire">
      <h2 class="title">{{ questionnaire.title }}</h2>
      <p class="description">{{ questionnaire.description }}</p>
      <van-form @submit="onSubmit">
        <div v-for="(q, index) in questions" :key="q.id" class="question-block">
          <div class="question-title">
            {{ index + 1 }}. {{ q.content }}
            <span v-if="q.required" class="required">*</span>
          </div>
          <div v-if="q.questionType === 'single'">
            <van-radio-group v-model="answers[q.id]">
              <van-radio v-for="opt in q.options" :key="opt.id" :name="opt.optionValue">
                {{ opt.optionLabel }}
              </van-radio>
            </van-radio-group>
          </div>
          <div v-else-if="q.questionType === 'multiple'">
            <van-checkbox-group v-model="answers[q.id]">
              <van-checkbox v-for="opt in q.options" :key="opt.id" :name="opt.optionValue">
                {{ opt.optionLabel }}
              </van-checkbox>
            </van-checkbox-group>
          </div>
          <div v-else-if="q.questionType === 'text'">
            <van-field 
              v-model="answers[q.id]" 
              type="textarea"
              :rows="3"
              placeholder="请输入您的答案"
              maxlength="500"
              show-word-limit
              autosize
            />
          </div>
        </div>
        <div style="margin: 24px 0;">
          <van-button round block type="primary" native-type="submit">提交答卷</van-button>
        </div>
      </van-form>
    </div>
    <van-empty v-else description="加载中..." />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showSuccessToast } from 'vant'
import { getQuestionnaireDetail, getQuestionList, getOptionList, submitAnswer, submitAnswerWithDetails } from '@/api/questionnaire'
import useUserStore from '@/store/modules/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const questionnaire = ref(null)
const questions = ref([])
const answers = reactive({})

function goBack() {
  router.back()
}

async function loadDetail() {
  const id = route.params.id
  console.log('开始加载问卷详情，ID:', id)
  
  try {
    // 先获取问卷详情
    console.log('正在获取问卷详情...')
    const qRes = await getQuestionnaireDetail(id)
    console.log('问卷详情响应:', qRes)
    
    if (qRes.code === 200) {
      questionnaire.value = qRes.data
      console.log('问卷详情设置成功:', questionnaire.value)
    } else {
      console.error('获取问卷信息失败:', qRes)
      showToast('获取问卷信息失败')
      return
    }
    
    // 再获取题目列表
    console.log('正在获取题目列表...')
    const qsRes = await getQuestionList(id)
    console.log('题目列表响应:', qsRes)
    
    if (qsRes.code === 200) {
      const qs = qsRes.rows || []
      console.log('获取到的题目列表:', qs)
      
      if (qs.length === 0) {
        console.warn('题目列表为空')
        showToast('该问卷暂无题目')
        questions.value = []
        return
      }
      
      // 处理每个题目
      for (const q of qs) {
        console.log(`处理题目${q.id}:`, q)
        // 使用后端返回的options字段（JSON序列化后的字段名）
        q.options = q.options || []
        console.log(`题目${q.id}的选项:`, q.options)
        
        // 初始化答案
        if (q.questionType === 'multiple') {
          answers[q.id] = []
        } else {
          answers[q.id] = ''
        }
      }
      questions.value = qs
      console.log('所有题目处理完成:', questions.value)
    } else {
      console.error('获取题目列表失败:', qsRes)
      showToast('获取题目信息失败')
      return
    }
  } catch (e) {
    console.error('加载问卷详情异常:', e)
    showToast('加载失败')
  }
}

function onSubmit() {
  // 简单校验
  for (const q of questions.value) {
    if (q.required) {
      if (q.questionType === 'text') {
        // 文本题校验：检查是否为空或只包含空格
        if (!answers[q.id] || answers[q.id].trim() === '') {
          showToast(`请完成第${index + 1}题`)
          return
        }
      } else {
        // 选择题校验：检查是否为空
        if (!answers[q.id] || (Array.isArray(answers[q.id]) && answers[q.id].length === 0)) {
          showToast(`请完成第${index + 1}题`)
          return
        }
      }
    }
  }
  
  // 构造提交数据
  const answerDetails = questions.value.map(q => {
    let optionValue = ''
    if (q.questionType === 'multiple') {
      // 多选题：数组转逗号分隔字符串
      optionValue = Array.isArray(answers[q.id]) ? answers[q.id].join(',') : answers[q.id]
    } else if (q.questionType === 'text') {
      // 文本题：去除首尾空格
      optionValue = answers[q.id] ? answers[q.id].trim() : ''
    } else {
      // 单选题：直接使用值
      optionValue = answers[q.id] || ''
    }
    
    return {
      questionId: q.id,
      optionValue: optionValue
    }
  })
  
  submitAnswerWithDetails({
    questionnaireId: questionnaire.value.id,
    userId: userStore.id, // 使用userStore.id而不是userStore.userId
    details: answerDetails
  }).then((res) => {
    if (res.code === 200) {
      showSuccessToast('提交成功')
      setTimeout(() => router.replace('/mobile-questionnaire-square'), 1200)
    } else {
      showToast(res.msg || '提交失败')
    }
  }).catch((error) => {
    console.error('提交失败:', error)
    showToast('提交失败，请重试')
  })
}

function goStats() {
  if (questionnaire.value) {
    router.push(`/mobile-questionnaire-stats/${questionnaire.value.id}`)
  }
}

onMounted(loadDetail)
</script>

<style scoped>
.mobile-questionnaire-detail {
  min-height: 100vh;
  background: #f7f8fa;
}
.content {
  padding: 16px;
}
.title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
}
.description {
  color: #666;
  margin-bottom: 16px;
}
.question-block {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.question-title {
  font-weight: 500;
  margin-bottom: 12px;
  font-size: 16px;
  color: #333;
}
.required {
  color: #fa541c;
  margin-left: 4px;
}

/* 自定义 Vant 组件样式 */
:deep(.van-radio-group) {
  margin-top: 8px;
}

:deep(.van-radio) {
  margin-bottom: 8px;
  padding: 8px 0;
}

:deep(.van-checkbox-group) {
  margin-top: 8px;
}

:deep(.van-checkbox) {
  margin-bottom: 8px;
  padding: 8px 0;
}

:deep(.van-field) {
  margin-top: 8px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

:deep(.van-field__control) {
  min-height: 80px;
  padding: 12px;
  font-size: 16px;
  line-height: 1.5;
}

:deep(.van-field__word-limit) {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

:deep(.van-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  height: 48px;
  font-size: 18px;
  font-weight: 600;
  border-radius: 24px;
}
</style> 